# Title     : TODO
# Objective : TODO
# Created by: xueyj
# Created on: 2020/10/09
pacman::p_load(dplyr, magrittr, lazyopt, stringr, ggplot2, crayon)

getnewdate <- function(path) {
  data <- path %>%
    read.delim(check.names = FALSE) %>%
    select(c("Time", "Weight",
             "vpd", "BARO/2/VP4",
             "DIELEC/0/5TM", "RH/2/VP4",
             "TEMP/0/5TM", "TEMP/2/VP4",
             "VAPORP/2/VP4", "vwc",
             "Tr"))
  k <- data %$% str_split(Time, " ")
  da <- NULL; ti <- NULL
  for (i in seq_along(k)) {
    da[i] <- k[[i]][1]; ti[i] <- k[[i]][2]
  }
  da %<>%
    as.character()
  ti %<>%
    as.character()

  data %>%
    mutate(date = da, time = ti) %>%
    select(c("date", "time", "Weight",
             "vpd", "BARO/2/VP4",
             "DIELEC/0/5TM", "RH/2/VP4",
             "TEMP/0/5TM", "TEMP/2/VP4",
             "VAPORP/2/VP4", "vwc", "Tr")) %>%
    return()
}

weightsmooth <- function(a, n = 30) {
  for (i in seq_along(a)) {
    a[i] <- mean(a[i:(i + n - 1)], na.rm = TRUE)
  }
  return(a)
}

bijiaoTime <- function(a, b) {
  a1 <- a %>%
    lazyopt::fenge() %>%
    as.numeric()
  b1 <- b %>%
    lazyopt::fenge() %>%
    as.numeric()
  if ((a1[1] * 60 + a1[2] - b1[1] * 60 - b1[2]) >= 0) {
    return(TRUE)
  }else {
    return(FALSE)
  }
}

getmebytime <- function(data, min, max, times) {
  list <- NULL
  for (i in seq_along(times)) {
    linshidata <- data[which(data$date == times[i]),]
    index <- NULL
    for (a in seq_len(nrow(linshidata))) {
      k <- linshidata[a, 2]
      index[a] <- ifelse((bijiaoTime(k, min) && bijiaoTime(max, k)), 1, 0)
    }
    list[i] <- linshidata[which(index == 1),] %$% mean(Weight)
  }
  data.frame(Time = times, mean = list) %>% return()
}

#需要修改 实时蒸腾速率（Tr），的地方，这里的算法需要修改可能
getme <- function(path) {
  data <- path %>%
    getnewdate() %>%
    set_colnames(c("date", "time", "Weight", "vpd", "BARO_2_VP4", "DIELEC_0_5TM", "RH_2_VP4",
                   "TEMP_0_5TM", "TEMP_2_VP4", "VAPORP_2_VP4", "vwc", "Tr"))
  times <- data %$% unique(date)
  Tr <- NULL;
  vpd <- NULL;
  BARO_2_VP4 <- NULL;
  DIELEC_0_5TM <- NULL;
  RH_2_VP4 <- NULL;
  TEMP_0_5TM <- NULL;
  TEMP_2_VP4 <- NULL
  VAPORP_2_VP4 <- NULL;
  vwc <- NULL

  for (i in seq_along(times)) {
    k <- which(data[, 1] == times[i])
    Tr[i] <- mean((data$Tr)[k])
    vpd[i] <- mean((data$vpd)[k])
    BARO_2_VP4[i] <- mean((data$BARO_2_VP4)[k])
    DIELEC_0_5TM[i] <- mean((data$DIELEC_0_5TM)[k])
    RH_2_VP4[i] <- mean((data$RH_2_VP4)[k])
    TEMP_0_5TM[i] <- mean((data$TEMP_0_5TM)[k])
    TEMP_2_VP4[i] <- mean((data$TEMP_2_VP4)[k])
    VAPORP_2_VP4[i] <- mean((data$VAPORP_2_VP4)[k])
    vwc[i] <- mean((data$vwc)[k])
  }

  m <- data %>%
    getmebytime("4:00", "4:30", times)
  e <- data %>%
    getmebytime("19:00", "19:30", times)
  mean <- data %>%
    getmebytime("00:00", "23:59", times)
  data <- data.frame(Time = m[, 1], m = m[, 2], e = e[, 2], mean = mean[, 2])
  data[, 1] %<>%
    as.character() %>%
    as.Date.character() %>%
    as.character()
  data %<>%
    mutate(E = m - e) %>%
    arrange(Time)
  data %<>%
    mutate(p = c((data$m[2:nrow(data)] - data$m[1:(nrow(data) - 1)]) %>%
                   as.numeric(), NA),
           Tr = Tr,
           vpd = vpd,
           BARO_2_VP4 = BARO_2_VP4,
           DIELEC_0_5TM = DIELEC_0_5TM,
           RH_2_VP4 = RH_2_VP4, TEMP_0_5TM = TEMP_0_5TM,
           TEMP_2_VP4 = TEMP_2_VP4,
           VAPORP_2_VP4 = VAPORP_2_VP4,
           vwc = vwc)

  return(data)
}

computed_ACCE_ACCP <- function(data) {
  ACCE <- NULL; ACCP <- NULL
  for (i in seq_len(nrow(data))) {
    ACCE[i] <- sum(data$E[1:i], na.rm = FALSE)
    ACCP[i] <- sum(data$p[1:i], na.rm = FALSE)
  }
  return(data %>% mutate(ACCE, ACCP))
}

computed_WUE_ESTP_PW <- function(data, baseweight) {
  plantweight <- NULL
  data %<>%
    mutate(WUE = ACCP / ACCE) %>%
    mutate(ESTP = WUE * E)
  for (i in seq_len(nrow(data))) {
    plantweight[i] <- baseweight + sum((data$ESTP)[1:i])
  }
  data %>%
    mutate(plantweight = plantweight) %>%
    return()
}

getRaWright <- function(grouppath, path) {
  group <- grouppath %>%
    read.delim(check.names = FALSE) %>%
    select(Name, PlantNetWeight)
  group[which(group$Name == (basename(path) %>%
    str_sub(., end = nchar(.) - 4))), 2] %>%
    as.numeric() %>%
    return()
}

#Gs_Gsc 都是通过Tr算出来的，不需要修改
add_Gs_Gsc <- function(data) {
  data %>%
    mutate(Gs = Tr / p) %>%
    mutate(Gsc = Gs / vpd) %>%
    return()
}

arg <- c("-i", "E:/projects/Lysimeter_Systems/src/output/A13.xls",
         "-g", "E:/projects/Lysimeter_Systems/src/data/plant3.xls",
         "-o", "E:/projects/Lysimeter_Systems/src/output2")

opt <- matrix(c(
  "inputfile", "i", 2, "character", "Set the input file path or packagepath", " ",
  "groupfile", "g", 2, "character", "Sets the packet file path", " ",
  "outputpackage", "o", 2, "character", "Set the output folder path", " "
), byrow = TRUE, ncol = 6) %>%
  lazyopt(arg=NULL)

filelist <- opt %$%
  dir(inputfile)

if (length(filelist) == 0) {

  opt %$%
    paste("read", inputfile) %>%
    print()
  result <- opt %$%
    getme(inputfile) %>%
    computed_ACCE_ACCP() %>%
    computed_WUE_ESTP_PW(., getRaWright(opt$groupfile, opt$inputfile)) %>%
    add_Gs_Gsc()

  result[is.na(result)] <- ""
  write.table(result,
              file = paste0(opt$outputpackage, "/", str_replace(opt$inputfile,
                                                                ".xls", "-l.xls") %>%
                basename()),
              sep = "\t",
              col.names = NA)

  print(paste("anlyze success"))
}else {
  for (i in seq_along(filelist)) {
    result <- opt %$%
      paste0(inputfile, "/", filelist[i]) %T>%
      print() %>%
      getme() %>%
      computed_ACCE_ACCP() %>%
      computed_WUE_ESTP_PW(., getRaWright(opt$groupfile, opt$inputfile)) %>%
      add_Gs_Gsc()

    result[is.na(result)] <- ""
    write.table(result,
                file = paste0(opt$outputpackage, "/",
                              str_replace(paste0(opt$inputfile, "/", filelist[i]), ".xls", "-l.xls") %>%
                                basename()),
                sep = "\t",
                col.names = NA)
    print(paste("anlyze success"))
  }
}





